<template>
  <div class="application-status">
    <!-- 搜索过滤区域 -->
    <div class="filter-bar">
      <div class="block">
        <span class="demonstration">关键字:</span>
        <input 
          type="text" 
          v-model="searchKeyword"
          placeholder="请输入标准名称或项目名称"
          class="custom-input"
          @input="handleSearch" />
      </div>
    </div>

    <!-- 添加加载状态 -->
    <div v-if="loading" class="loading-container">
      <el-loading-spinner></el-loading-spinner>
      <p>数据加载中...</p>
    </div>

    <!-- 添加错误提示 -->
    <el-alert
      v-if="error"
      :title="error"
      type="error"
      show-icon
      @close="error = null">
    </el-alert>

    <!-- 表格区域 -->
    <table v-if="!loading && !error">
      <thead>
        <tr>
          <th>序号</th>
          <th>标准名称</th>
          <th>项目名称</th>
          <th>培训证书</th>
          <th>培训完成时间</th>
          <th>授权证书</th>
        </tr>
      </thead>
      <tbody>
        <tr v-for="(item, index) in paginatedData" :key="index">
          <td>{{ (currentPage - 1) * pageSize + index + 1 }}</td>
          <td>{{ item.staName }}</td>
          <td>{{ item.pjName }}</td>
          <td>
            <el-button 
              v-if="item.trainCertificate" 
              @click="downloadPdf(item.trainCertificate)" 
              type="text" 
              size="small">
              <i class="el-icon-download"></i> 点击下载
            </el-button>
            <el-tag v-else type="info" size="small">暂无证书</el-tag>
          </td>
          <td>{{ item.finishTime }}</td>
          <td>
            <el-button 
              v-if="item.authorCertificate" 
              @click="downloadPdf(item.authorCertificate)" 
              type="text" 
              size="small">
              <i class="el-icon-download"></i> 点击下载
            </el-button>
            <el-tag v-else type="info" size="small">暂无证书</el-tag>
          </td>
        </tr>
      </tbody>
    </table>

    <!-- 分页器 -->
    <div class="pagination-container">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page.sync="currentPage"
        :page-sizes="[10, 15, 20, 30]"
        :page-size="pageSize"
        :total="totalItems"
        layout="total, sizes, prev, pager, next, jumper"
        background>
      </el-pagination>
    </div>
  </div>
</template>

<script>
import pdf from 'vue-pdf';

export default {
  components: { pdf },
  data() {
    return {
      activeTab: 'first',
      certificateData: [],
      currentData: [],
      pageSize: 10,
      currentPage: 1,
      totalItems: 0,
      loading: false,
      error: null,
      searchKeyword: '',
      searchTimeout: null
    };
  },
  created() {
    this.fetchCertificates();
  },
  methods: {
    async fetchCertificates() {
      this.loading = true;
      try {
        const response = await this.$http.get("/findPmcByUID");
        this.certificateData = response.data.reduce((acc, item) => {
          const projectIndex = acc.findIndex(project => 
            (project.pjName === item.pjName && project.staName === item.staName)
          );
          if (projectIndex !== -1) {
            if (item.pmcType === 1) {
              acc[projectIndex].trainCertificate = item.pmcId;
              acc[projectIndex].finishTime = item.pmcTime;
            } else {
              acc[projectIndex].authorCertificate = item.pmcId;
            }
          } else {
            acc.push({
              staName: item.staName,
              pjName: item.pjName,
              finishTime: item.pmcTime,
              [(item.pmcType === 1) ? 'trainCertificate' : 'authorCertificate']: item.pmcId
            });
          }
          return acc;
        }, []);
        
        this.currentData = this.certificateData;
        this.totalItems = this.certificateData.length;
        
        // 添加调试日志
        console.log('Fetched data:', this.certificateData);
        console.log('Current data:', this.currentData);
        
      } catch (error) {
        this.error = '获取证书数据失败';
        console.error('Error:', error);
      } finally {
        this.loading = false;
      }
    },
    handleSearch() {
      if (this.searchTimeout) {
        clearTimeout(this.searchTimeout);
      }
      this.searchTimeout = setTimeout(() => {
        this.currentPage = 1; // 重置页码
        this.totalItems = this.filteredData.length;
      }, 300);
    },
    async downloadPdf(pmcId) {
      try {
        this.loading = true;
        const response = await this.$http.get(`/downloadPmc/${pmcId}`);
        const fileUrl = response.data;
        const link = document.createElement('a');
        link.href = fileUrl;
        const filename = response.data.fileName || '证书.pdf';
        link.setAttribute('download', filename);
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
        this.$message.success('下载成功');
      } catch (error) {
        this.$message.error('下载失败,请稍后重试');
        console.error('下载失败:', error);
      } finally {
        this.loading = false;
      }
    },
    handleSizeChange(val) {
      this.pageSize = val;
      this.currentPage = 1;
    },
    handleCurrentChange(val) {
      this.currentPage = val;
      window.scrollTo({
        top: 0,
        behavior: 'smooth'
      });
    },
    indexMethod(index) {
      return (this.currentPage - 1) * this.pageSize + index + 1;
    }
  },
  computed: {
    filteredData() {
      if (!this.searchKeyword) {
        return this.currentData;
      }
      const keyword = this.searchKeyword.toLowerCase();
      return this.currentData.filter(item => 
        item.staName.toLowerCase().includes(keyword) ||
        item.pjName.toLowerCase().includes(keyword)
      );
    },
    paginatedData() {
      const start = (this.currentPage - 1) * this.pageSize;
      const end = this.currentPage * this.pageSize;
      return this.filteredData.slice(start, end);
    }
  }
};
</script>

<style scoped>
.application-status {
  padding: 20px;
  background-color: #f9f9f9;
  border-radius: 8px;
}

.filter-bar {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  margin-bottom: 20px;
  align-items: center;
}

.filter-bar input.custom-input {
  padding: 8px 15px;
  border: 1px solid #ccc;
  border-radius: 4px;
  font-size: 14px;
  transition: border-color 0.3s ease, background-color 0.3s ease;
  width: 200px;
}

.filter-bar input.custom-input:hover,
.filter-bar input.custom-input:focus {
  border-color: #4CAF50;
  background-color: #fff;
  outline: none;
}

.block {
  display: flex;
  align-items: center;
}

.demonstration {
  margin-right: 10px;
  font-weight: bold;
}

table {
  width: 100%;
  border-collapse: collapse;
  background-color: #fff;
  margin-bottom: 20px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

th, td {
  padding: 12px 16px;
  text-align: center;
  border: 1px solid #EBEEF5;
}

th {
  background-color: #F5F7FA;
  color: #606266;
  font-weight: 500;
  font-size: 14px;
  height: 40px;
  line-height: 40px;
}

td {
  color: #606266;
  font-size: 14px;
  height: 50px;
  line-height: 50px;
}

tr:hover td {
  background-color: #F5F7FA;
}

.loading-container {
  text-align: center;
  padding: 40px 0;
}

.loading-container p {
  color: #909399;
  margin-top: 10px;
}

.pagination-container {
  padding: 20px;
  text-align: center;
  background: white;
  border-top: 1px solid #EBEEF5;
}

/* Element UI 组件样式 */
:deep(.el-button--text) {
  color: #4CAF50;
  padding: 0;
}

:deep(.el-button--text:hover) {
  color: #45a049;
}

:deep(.el-button--text i) {
  margin-right: 4px;
}

:deep(.el-tag--info) {
  background-color: #f4f4f5;
  border-color: #e9e9eb;
  color: #909399;
}

:deep(.el-pagination) {
  font-weight: normal;
  color: #606266;
}

:deep(.el-pagination.is-background .el-pager li:not(.disabled).active) {
  background-color: #4CAF50;
  color: white;
}

:deep(.el-pagination.is-background .el-pager li:not(.disabled):hover) {
  color: #4CAF50;
}

:deep(.el-pagination .el-select .el-input) {
  width: 110px;
}

:deep(.el-pagination__sizes) {
  margin-right: 15px;
}

:deep(.el-pagination__total) {
  margin-right: 15px;
}
</style>
